<?php

namespace app\admin\controller\newhouse\customer;

use app\common\controller\Backend;
use think\Db;
use think\Log;

/**
 * 新房客户
 *
 * @icon fa fa-circle-o
 */
class Items extends Backend
{
    
    /**
     * customer模型对象
     * @var \app\admin\model\newhouse\customer\Items
     */
    protected $model = null;
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\newhouse\customer\Items;
        $this->view->assign("sexRadioList", $this->model->getSexRadioList());
        $this->view->assign("marriageRadioList", $this->model->getMarriageRadioList());
        $this->view->assign("firstHouseRadioList", $this->model->getFirstHouseRadioList());
        $this->view->assign("socialSecurityRadioList", $this->model->getSocialSecurityRadioList());
        $this->view->assign("paymentMethodRadioList", $this->model->getPaymentMethodRadioList());

    }

    
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 代理商 开发商权限设置

            $where_customer_limit="1=1";

            /////////// 找到报备过的楼盘
            $where1='1=1';
            $group = $this->auth->getGroups()[0];
            $group_name=$group['name'];
            // var_dump($group_name);die();
            if($group_name =='楼盘开发商' || $group_name=='楼盘代理公司'){
                //看到本公司所有客户
                // if($group_name=='楼盘开发商'){
                //     $where1 .= " AND developer_adminid=".$this->auth->id;
                // }else if($group_name=='楼盘代理'){
                //     $where1 .= " AND agent_adminid=".$this->auth->id;
                // }
                // $build_list = \app\admin\model\newhouse\building\Items::all($where1);
               
                // $str='';
                // foreach($build_list as $key=>$value){
                //     if($str!='')$str.=',';
                //     $str .= $value->id;
                // }
                // $where_customer_limit .= " AND building_id in($str)";
                 $where_customer_limit = 'admin.cop_id='.$this->auth->cop_id;
                Log::info($where_customer_limit);
            }else if($group_name=='代理商案场负责人' || $group_name=='开发商案场负责人'){
                // 只能看到自己的客户
                $where_customer_limit = 'create_userid='.$this->auth->id;
            }
            else if($group_name=='Admin group' ){
                
            }else{
                $where_customer_limit = "create_userid=" . $this->auth->id;
            }
            /////////////
            
            $total = $this->model->alias(['mf_newhouse_customer_items'=>'customer'])->with(['admin'])
                ->where($where)
                ->where($where_customer_limit)
                ->order($sort, $order)
                ->count();
            $list = $this->model->alias(['mf_newhouse_customer_items'=>'customer'])->with(['admin'])
                ->where($where)
                ->where($where_customer_limit)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
         
            foreach ($list as $row) {
                // 如果是自己在看，就不要*替换
                if($row->hide_mobile)
                    $row->customer_tel=substr_replace($row->customer_tel,'****',3,4);
                
                $row->getRelation('admin')->visible(['nickname']);
                // $row->getRelation('newhousecustomeritems')->visible(['customer_name']);
            }
            
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if(isset($params['want_area'])){
                    $array=explode('/',$params['want_area']);

                    if(sizeof($array)>0) $params['want_province']=$array[0];
                    if(sizeof($array)>1) $params['want_city']=$array[1];
                    if(sizeof($array)>2) $params['want_district']=$array[2];
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $params['create_userid'] = $this->auth->id;
                $params['cop_id'] = $this->auth->cop_id;
                // 客户判重
                $tel =trim( $params['customer_tel']);
                $whereexists="customer_tel = '" . $tel . "' OR customer_tel2='" . $tel . "' OR customer_tel3='" . $tel . "'";
                $has = $this->model->where($whereexists)->count();
                if($has>0){
                    $this->error('号码已经存在');
                    return;
                }

                $tel =trim( $params['customer_tel2']);
                if(!empty($tel)){
                    $whereexists="customer_tel = '" . $tel . "' OR customer_tel2='" . $tel . "' OR customer_tel3='" . $tel . "'";
                    $has = $this->model->where($whereexists)->count();
                    if($has>0){
                        $this->error('号码已经存在');
                        return;
                    }
                }
                
                $tel =trim( $params['customer_tel3']);
                if(!empty($tel)){
                    $whereexists="customer_tel = '" . $tel . "' OR customer_tel2='" . $tel . "' OR customer_tel3='" . $tel . "'";
                    $has = $this->model->where($whereexists)->count();
                    if($has>0){
                        $this->error('号码已经存在');
                        return;
                    }
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if(isset($this->model->building_id)){
                        /// 报备同步写到报备表里
                        $report = new \app\admin\controller\newhouse\report\Items;
                        $report->sync($this->model->id,$this->model->building_id);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if(isset($params['want_area'])){
                    $array=explode('/',$params['want_area']);

                    if(sizeof($array)>0) $params['want_province']=$array[0];
                    if(sizeof($array)>1) $params['want_city']=$array[1];
                    if(sizeof($array)>2) $params['want_district']=$array[2];
                }
                unset($params['customer_tel']);
                $params['cop_id'] = $this->auth->cop_id;
                $params['update_userid'] = $this->auth->id;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);       
                    /// 报备同步写到报备表里
                    $report = new \app\admin\controller\newhouse\report\Items;
                    $report->sync($ids,$row->building_id);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function view($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $building_model = \app\admin\model\newhouse\building\Items::all("building_id in($row->building_id)");
        $follow_model = new \app\admin\model\newhouse\customer\Follow;
        $follow_list=$follow_model->where(['customer_id'=>$ids])->select();

        $report_model =new \app\admin\model\newhouse\report\Items;
        $report_list = $report_model->where(['customer_id'=>$ids])->with(['newhousecreateadmin','newhouseverifyadmin','newhousebuilding','newhousecustomer'])->select();

        $this->view->assign('follow_list',$follow_list);
        $this->view->assign('report_list',$report_list);
        $this->view->assign('buildings',$building_model);
        $this->view->assign("row", $row);
        $this->view->assign("customer_id",$ids);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    // 同时把跟进记录和报备记录也删除
                    $follow_list = \app\admin\model\newhouse\customer\Follow::all(['customer_id'=>$v->id]);
                    foreach($follow_list as $k1=>$v1){
                        $v1->delete();
                    }
                    $report_list = \app\admin\model\newhouse\report\Items::all(['customer_id'=>$v->id]);
                    foreach($report_list as $k2=>$v2){
                        $v2->delete();
                    }
                }

                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    public function querytel(){
        $tel = $this->request->request('tel');
        $list=\app\admin\model\newhouse\customer\Items::all(['customer_tel'=>$tel]);
        if(!empty($list)){
            return json(['exists'=>true]);
        }else
            return json(['exists'=>false]);
    }
}
